class TasksController < ApplicationController
  before_action :set_task, only: [:show, :edit, :update, :destroy, :censor, :view]

  # GET /tasks
  # GET /tasks.json
  def index
    @tasks = Task.all
  end

  # GET /tasks/1
  # GET /tasks/1.json
  def show
  end

  # GET /tasks/new
  def new
    @task = Task.new
  end

  # GET /tasks/1/edit
  def edit
  end

  # POST /tasks
  # POST /tasks.json
  def create
    @task = Task.new(task_params)
    
    respond_to do |format|
      if @task.save
        # Parse benchmark
        sample_file = File.new(params[:sample_file].tempfile, 'r')
        # Prepare uuid table
        nsample = 0
        nfinger = 0
        finger_uuids = @task.fingers.map(&:uuid)
        sample_uuids = @task.samples.map(&:uuid)
        sample_file.each do |line|
          fingeruuid, sampleuuid, path = line.split(' ')
          if !finger_uuids.include? fingeruuid
            @task.fingers.create(uuid: fingeruuid)
            finger_uuids.push fingeruuid
          end

          if !sample_uuids.include? sampleuuid
            @task.samples.create(uuid: sampleuuid, 
                              finger_id: @task.fingers.where(uuid: fingeruuid).first.id, 
                              path: path, 
                              task_id: @task.id)
            sample_uuids.push sampleuuid
          end
        end

        format.html { redirect_to @task, notice: 'Task was successfully created. ' }
        format.json { render :show, status: :created, location: @task }
      else
        format.html { render :new }
        format.json { render json: @task.errors, status: :unprocessable_entity }
      end
    end
  end

  # PATCH/PUT /tasks/1
  # PATCH/PUT /tasks/1.json
  def update
    respond_to do |format|
      if @task.update(task_params)
        format.html { redirect_to @task, notice: 'Task was successfully updated.' }
        format.json { render :show, status: :ok, location: @task }
      else
        format.html { render :edit }
        format.json { render json: @task.errors, status: :unprocessable_entity }
      end
    end
  end

  # DELETE /tasks/1
  # DELETE /tasks/1.json
  def destroy
    @task.destroy
    respond_to do |format|
      format.html { redirect_to tasks_url, notice: 'Task was successfully destroyed.' }
      format.json { head :no_content }
    end
  end

  def censor
    @finger = @task.fingers.pending.limit(10).sample
    @sample1, @sample2 = @finger.generate_match
    @finger2 = @sample2.finger
    if @task.finished?
      redirect_to task_path(@task), notice: 'Congradulations'
      return
    end
  end

  def view
    render plain: @task.get_view
  end

  private
    # Use callbacks to share common setup or constraints between actions.
    def set_task
      @task = Task.find(params[:id])
    end

    # Never trust parameters from the scary internet, only allow the white list through.
    def task_params
      params[:task].permit(:name, :num_of_samples, :num_of_fingers)
    end
end
